package io.p2p.stream.dispatch.handler;

import com.alibaba.fastjson.JSONObject;
import common.core.domain.udp.UdpApiProtocol;
import io.netty.buffer.Unpooled;
import io.netty.channel.socket.DatagramPacket;
import io.p2p.stream.dispatch.model.ClientSharedModel;
import io.p2p.stream.dispatch.task.MainServerHeartbeatTask;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

public class MainlineLoginAckHandler{

    private UdpApiProtocol apiProtocol;

    public MainlineLoginAckHandler(UdpApiProtocol apiProtocol) {
        this.apiProtocol = apiProtocol;
    }

    public void mainlineLoginAck() {
        boolean success = apiProtocol.getBuffer().getBooleanValue("success");

        if(success){

            apiProtocol.getCtx().executor().scheduleAtFixedRate(new MainServerHeartbeatTask(ClientSharedModel.loginName,
                    ClientSharedModel.mainServerFirstIP,
                    ClientSharedModel.mainServerFirstPort,
                    apiProtocol.getCtx().channel()),0,5, TimeUnit.SECONDS);

            JSONObject natCheck = new JSONObject();
            natCheck.put("type","natCheck");
            natCheck.put("subType","step1");
            natCheck.put("name",ClientSharedModel.loginName);

            apiProtocol.getCtx().writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(natCheck.toJSONString(), StandardCharsets.UTF_8),
                    new InetSocketAddress(ClientSharedModel.stunServerIP,ClientSharedModel.stunServerPort)));

        }
    }
}
